package main.com.votes.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnDB {
	private static final String URL = "jdbc:mysql://localhost:3306/votes?serverTimezone=GMT%2B8&useUnicode=true&characterEncodeing=UTF-8&useSSL=false";
	private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	private static final String USER = "root";
	private static final String PASSWORD = "root";

	static Connection conn = null;
	static PreparedStatement ps = null;
	static ResultSet rs = null;

	//连接数据库
	public static Connection getConnection() {
		try {
			//1.加载数据库驱动。
			Class.forName(DRIVER);

			//2.建立数据库连接
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return conn;
	}

	public static void closeDB(Object o, PreparedStatement pst, Connection conn) {
	}

	public static int executeUpdate(String sql, Object object[]) {
		int flag = 0;
		try {
			ps = conn.prepareStatement(sql);
			if (object != null) {
				for (int i = 0; i < object.length; i++) {
					ps.setObject(i + 1, object[i]);
				}
			}
			flag=ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return flag;
	}

	public static ResultSet  executeQuery(String sql,Object object[]){
		try {
			ps = conn.prepareStatement(sql);
			if (object != null) {
				for (int i = 0; i < object.length; i++) {
					ps.setObject(i + 1, object[i]);
				}
			}
			rs=ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	
	public static void close() {
		
			try {
				if(conn!=null){
					conn.close();
				}
				if(ps!=null){
					ps.close();
				}
				if(rs!=null){
					rs.close();
				}
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		
	}

}
